package com.lz.gmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lz.gmall.product.entity.BaseAttrInfo;
import com.lz.gmall.product.entity.BaseAttrValue;
import com.lz.gmall.product.service.BaseAttrInfoService;
import com.lz.gmall.product.mapper.BaseAttrInfoMapper;
import com.lz.gmall.product.service.BaseAttrValueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class BaseAttrInfoServiceImpl extends ServiceImpl<BaseAttrInfoMapper, BaseAttrInfo>
    implements BaseAttrInfoService{

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    private BaseAttrValueService baseAttrValueService;

    /**
     * 根据id获取平台属性和平台属性值
     * @param c1Id 一级分类id
     * @param c2Id 二级分类id
     * @param c3Id 三级分类id
     * @return 根据产品的id 获取该产品的平台属性
     */
    @Override
    public List<BaseAttrInfo> getBaseAttrInfoPage(Long c1Id, Long c2Id, Long c3Id) {
        return baseAttrInfoMapper.getBaseAttrInfoPage(c1Id,c2Id,c3Id);
    }

    /**
     * 添加产品的平台属性和平台属性值
     * 修改产品的平台属性和平台属性值
     * @param baseAttrInfo 产品的平台属性和属性值信息
     */
    @Override
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {

        if (baseAttrInfo.getId() == null){
            //直接添加平台属性
            this.save(baseAttrInfo);

            //添加平台属性值
            List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
            //平台属性值没有属性id，根据id回显，获取平台属性id
            attrValueList = attrValueList.stream().map(baseAttrValue -> {
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                return baseAttrValue;
            }).collect(Collectors.toList());

            baseAttrValueService.saveBatch(attrValueList);
        }else {//修改平台属性和平台属性值

            //直接修改平台属性
            this.updateById(baseAttrInfo);

            //修改平台属性值，前端操作可能存在删除属性值，新增属性值
            //解决方案：把该平台属性对于的属性值全部删除，重新加入
            List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
            //删除属性值
            LambdaQueryWrapper<BaseAttrValue> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(BaseAttrValue::getAttrId,baseAttrInfo.getId());
            baseAttrValueService.remove(wrapper);

            //添加属性值
            attrValueList = attrValueList.stream().map(baseAttrValue -> {
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                return baseAttrValue;
            }).collect(Collectors.toList());

            baseAttrValueService.saveBatch(attrValueList);
        }

    }
}




